package com.panshi.modules.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.panshi.api.UserApi;
import com.panshi.modules.domain.*;
import com.panshi.modules.service.*;
import com.panshi.vo.ItemQueryUserVo;
import com.panshi.vo.R;
import com.panshi.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Pattern;

@Slf4j
@Api(tags = "用户登录注册接口")
@RestController
@RequestMapping(value = "/user",produces = "application/json")
public class UserController implements UserApi {

    @Autowired
    private UserService userService;

    @Autowired
    private VerifyCodeService verifyCodeService;

    @Autowired
    private UserDynamicService userDynamicService;

    @Autowired
    private UserCollectService userCollectService;

    @Autowired
    private UserNoticeService userNoticeService;

    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public R userLogin(@RequestBody String principle) {
        log.info("======================{}==================", principle);
        UserVO userVO = null;
        Pattern pattern = Pattern.compile("^1[3|4|5|6|7|8|9][0-9]{9}$");
        boolean matches = pattern.matcher(principle).matches();
        if (matches) {
            userVO = userService.getUserByPhone(principle);
        } else {
            userVO = userService.getUserByEmail(principle);
        }
        if (userVO == null) {
            return R.error();
        } else {
            return R.ok().data("data", JSONObject.toJSONString(userVO));
        }
    }

    @PostMapping("/register")
    @ApiOperation("用户注册接口")
    public R userRegister(@RequestBody UserVO userVO) {
        if(redisTemplate.hasKey("user:code:"+userVO.getUsername()) && !redisTemplate.opsForValue().get("user:code:"+userVO.getUsername()).equals(userVO.getVerifyCode())){
            return R.error().msg("输入验证码错误");
        }
        UserVO user = null;
        UserMember userMember = new UserMember();
        Pattern pattern = Pattern.compile("^1[3|4|5|6|7|8|9][0-9]{9}$");
        boolean matches = pattern.matcher(userVO.getUsername()).matches();
        int type = -1;
        if (matches) {
            type = 0;
            user = userService.getUserByPhone(userVO.getUsername());
            userMember.setNickname(userVO.getUsername().substring(0,8));
            userMember.setPhone(userVO.getUsername());
        } else {
            type = 1;
            user = userService.getUserByEmail(userVO.getUsername());
            userMember.setNickname(userVO.getUsername().substring(0,11));
            userMember.setEmail(userVO.getUsername());
        }
        if (null == user) {
            userMember.setPassword(userVO.getPassword());
            userService.addUser(userMember);
            int id = userMember.getId();
            return R.ok().data("data",id);
        }
        return R.error().msg("该用户名已经存在,请重新输入");
    }

    @PostMapping("/getUserId")
    @ApiOperation("获取用户ID")
    public R getUserId(@RequestBody String userName) {
        Pattern pattern = Pattern.compile("^1[3|4|5|6|7|8|9][0-9]{9}$");
        boolean matches = pattern.matcher(userName).matches();
        Long userId;
        if (matches) {
            userId = userService.getUserLoginId(userName,1);
        } else {
            userId = userService.getUserLoginId(userName,2);
        }
        return R.ok().data("userId",userId);
    }

    @PostMapping("/verifyCode")
    @ApiOperation("发送登录验证码接口")
    public R verifyCode(@RequestBody @ApiParam(name = "username", required = true) String username) {

        Pattern pattern = Pattern.compile("^1[3|4|5|6|7|8|9][0-9]{9}$");
        boolean matches = pattern.matcher(username).matches();

        boolean flag = false;
        if (matches) {
            UserVO userByPhone = userService.getUserByPhone(username);
            if (userByPhone == null) {
                return R.error().msg("没有此账号,请先注册1");
            }
            flag = verifyCodeService.sendSms(username);
        } else {
            UserVO userByEmail = userService.getUserByEmail(username);
            if (userByEmail == null) {
                return R.error().msg("没有此账号,请先注册2");
            }
            flag = verifyCodeService.sendEmail(username);
        }

        if (flag) {
            return R.ok();
        }
        return R.error().msg("验证已发送");
    }

    @PostMapping("/verifyCodeRegitser")
    @ApiOperation("发送注册验证码接口")
    public R verifyCodeRegitser(@RequestBody @ApiParam(name = "username", required = true) String username) {

        Pattern pattern = Pattern.compile("^1[3|4|5|6|7|8|9][0-9]{9}$");
        boolean matches = pattern.matcher(username).matches();

        boolean flag = false;
        if (matches) {
            flag = verifyCodeService.sendSms(username);
        } else {
            flag = verifyCodeService.sendEmail(username);
        }
        if (flag) {
            return R.ok().msg("验证码已发送11");
        }
        return R.error().msg("验证码发送失败22");
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/verifyLogin")
    @ApiOperation("验证码登录接口")
    public R verifyLogin(@RequestBody String username) {
        System.out.println("-------------------" + username + "==============================");
        if (!redisTemplate.hasKey("user:code:" + username)) {
            return R.error().msg("验证码不存在");
        }
        String code = redisTemplate.opsForValue().get("user:code:" + username);
        UserVO userVO = new UserVO();
        userVO.setUsername(username);
        userVO.setVerifyCode(code);
        return R.ok().data("data", username);

    }

    @GetMapping("/center/getUserInfo")
    @ApiOperation("查询前台用户个人信息")
    public R getUserInfo(@RequestParam("id") Long id) {

        UserMember userMember = userService.selectByUserInfo(id.intValue());

        userMember.setPassword(null);


        UserDetailResult result = new UserDetailResult();

        result.setUserMember(userMember);

        return R.ok().data("userMemberInfo", JSONObject.toJSONString(result));
    }


    @PutMapping(value = "/center/updateUserInfo", produces = "application/json")
    @ApiOperation("修改前台用户个人信息")
    public R updateUserInfo(@RequestBody ItemQueryUserVo itemQueryVo) {

        int count = userService.updateUserInfo(itemQueryVo);

        if(count > 0){
            return R.ok().msg("修改用户个人信息成功");
        }

        return R.error().msg("修改用户个人信息失败");
    }

    @PutMapping(value = "/center/update/updatePwd")
    @ApiOperation("修改个人密码")
    public R updatePwd(@RequestBody ItemQueryUserVo itemQueryVo) {

        UserMember userMember = userService.selectByUserInfo(itemQueryVo.getId().intValue());

        if (itemQueryVo.getOldPwd().equals(userMember.getPassword())) {
            userMember.setPassword(itemQueryVo.getPwd());
            userService.updateUserInfo(itemQueryVo);
            return R.ok().msg("修改密码成功");
        }

        return R.error().msg("原密码错误,修改密码失败");
    }

    @PutMapping(value = "/center/update/updateUserHeadBaseCode")
    @ApiOperation("修改个人头像")
    public R updateUserHeadBaseCode(@RequestBody ItemQueryUserVo itemQueryVo) {

        String url = userService.updateUserHeadBaseCode(itemQueryVo);

        if(!StringUtils.isEmpty(url)){
            return R.ok().msg("修改个人头像成功").data("data",url);
        }

        return R.error().msg("修改个人头像失败");
    }


    @PostMapping(value ="/center/index")
    @ApiOperation("查询个人动态信息")
    public R userIndex(@RequestBody ItemQueryUserVo itemQueryVoParam) {
        System.out.println("itemQueryVoParam            "+itemQueryVoParam);
        //用户个人信息
        UserMember userMember = userService.selectByUserInfo(itemQueryVoParam.getId().intValue());
        userMember.setPassword(null);
        //返回对象
        UserDetailResult result = new UserDetailResult();
        //将用户的个人信息存储到返回对象
        result.setUserMember(userMember);
        //获取个人收藏总记录数
        int collect = userCollectService.selectCollectCount(itemQueryVoParam.getId());
        //获取问题,回答,文章总计录数
        List<UserDynamicCount> list = userDynamicService.selectResultMapCount(itemQueryVoParam);
        result.setCountList(list);
        result.setCollectNum(collect);
        return R.ok().data("userMemberOne",JSONObject.toJSONString(result));
    }

    @PostMapping(value ="/index/dy/list")
    @ApiOperation("查询个人动态信息列表")
    public R dyList(@RequestBody ItemQueryUserVo itemQueryVoParam) {

        //动态集合
        List<UserDynamicRelevance> userDynamicRelevanceicList = userDynamicService.findUserDynamicList(itemQueryVoParam);

        //返回对象
        UserDetailResult result = new UserDetailResult();
        //将查询的动态集合存储到返回对象
        result.setUserDynamicRelevanceList(userDynamicRelevanceicList);

        return R.ok().data("userDynamicRelevanceList",JSONObject.toJSONString(result));
    }

    @DeleteMapping("/center/public/del")
    @ApiOperation("删除个人动态")
    public R delDy(@RequestParam("id")int id){
        int count = userDynamicService.deleteUserDynamic(id);

        if(count>0){
            return R.ok().msg("删除个人动态成功");
        }

        return R.error().msg("删除个人动态失败");
    }

    @DeleteMapping("/collect/del")
    @ApiOperation("删除个人收藏")
    public R delCollect(@RequestParam("id")Long id){
        //删除个人收藏
        int count = userCollectService.deleteUserCollect(id);

        if(count>0){
            return R.ok().msg("删除个人收藏成功");
        }

        return R.error().msg("删除个人收藏失败");
    }






    @RequestMapping(value = "/center/update/sendEmail/{userId}/{userName}/{type}",method = RequestMethod.GET)
    @ApiOperation("发送修改邮箱验证码")
    public R sendEmail(@PathVariable("userId")Integer userId,@PathVariable("userName")String userName,@PathVariable("type")String type){
        return userService.sendEmail(userId,userName,type);
    }

    @RequestMapping(value = "/center/update/confirm/email/{userId}/{userName}/{code}/{type}",method =RequestMethod.POST)
    @ApiOperation("检验邮箱验证码是否正确")
    public R checkEmailCode(@PathVariable("userId")Integer userId,@PathVariable("userName")String userName,@PathVariable("code")String code,@PathVariable("type")String type){
        R r =userService.checkEmailCode(userId,userName,code,type);
        return r;
    }

    @RequestMapping(value = "/center/update/sendIphone/{userId}/{userName}/{type}",method = RequestMethod.GET)
    @ApiOperation("发送手机短信验证码")
    public R sendIphone(@PathVariable("userId")Integer userId,@PathVariable("userName")String userName,@PathVariable("type")String type){
        return userService.sendIphone(userId,userName,type);
    }

    @RequestMapping(value = "/center/update/confirm/iphone/{userId}/{userName}/{code}/{type}",method =RequestMethod.POST)
    @ApiOperation("检验短信验证码是否正确")
    public R checkIphoneCode(@PathVariable("userId")Integer userId,@PathVariable("userName")String userName,@PathVariable("code")String code,@PathVariable("type")String type){
        R r =userService.checkIphoneCode(userId,userName,code,type);
        return r;
    }

    @GetMapping("/index/msg/read")
    @ApiOperation("个人站内消息阅读")
    public R readNotice(@RequestParam("ids")int id){
        int count = userNoticeService.updateRead(id);
        if(count>0){
            return R.ok().msg("个人站内消息阅读成功");
        }

        return R.error().msg("个人站内消息阅读失败");
    }

    @GetMapping(value = "/index/getNoReadCount")
    @ApiOperation("个人站内消息未读数")
    public R getNoReadCount(@RequestParam("id")int id){

        List<UserNoticeRead> userNoticeReadList = userNoticeService.getNoReadCount(id);

        if(userNoticeReadList != null){
            return R.ok().msg("个人站内消息阅读成功").data("data", JSONArray.toJSONString(userNoticeReadList));
        }

        return R.error().msg("个人站内消息阅读失败");
    }

    @PostMapping("/index/qalist")
    @ApiOperation("查询个人提问列表")
    public R qaList(@RequestBody ItemQueryUserVo itemQueryVo){
        //查询动态表里问题数据列表
        List<UserDynamicQuestion> qaQuestionList =  userDynamicService.findQaQuestionDynamicList(itemQueryVo);

        //返回对象
        UserDetailResult result = new UserDetailResult();
        //将查询动态表里问题数据列表存储到返回对象里面
        result.setUserDynamicQuestionList(qaQuestionList);

        return  R.ok().data("qaQuestionList",JSONObject.toJSONString(result));
    }

    @PostMapping("/index/qaReplylist")
    @ApiOperation("查询个人回答列表")
    public R answerList(@RequestBody ItemQueryUserVo itemQueryVo){


        //查询未审核回答表数据列表
        List<UserDynamicAnswer> qaAnswerList = userDynamicService.findQaAnswerDynamicList(itemQueryVo);
        //返回对象
        UserDetailResult result = new UserDetailResult();
        //将查询动态表里回答数据列表到返回对象里面
        result.setUserDynamicAnswerList(qaAnswerList);

        return  R.ok().data("qaAnswerList",JSONObject.toJSONString(result));
    }

    @PostMapping("/index/articlelist")
    @ApiOperation("查询个人资讯列表")
    public R zxList(@RequestBody ItemQueryUserVo itemQueryVo){

        //查询未审核资讯表数据列表
        List<UserDynamicZx> zxList = userDynamicService.findZxDynamicList(itemQueryVo);
        //返回对象
        UserDetailResult result = new UserDetailResult();
        //将查询动态表里资讯数据列表返回对象里面
        result.setUserDynamicZxList(zxList);

        return  R.ok().data("zxList",JSONObject.toJSONString(result));
    }

    @PostMapping("/index/collectList")
    @ApiOperation("查询个人收藏列表")
    public R collectList(@RequestBody ItemQueryUserVo itemQueryVo){

        //查询收藏表数据列表
        List<UserCollect> userCollectList = userCollectService.findUserCollectList(itemQueryVo);
        //返回对象
        UserDetailResult result = new UserDetailResult();
        //将查询查询收藏表数据列表返回对象里面
        result.setUserCollectList(userCollectList);
        return  R.ok().data("userCollectList",JSONObject.toJSONString(result));
    }


    @PostMapping(value = "/index/msg/list")
    @ApiOperation("查询个人站内消息列表")
    public R msgList(@RequestBody ItemQueryUserVo itemQueryVo){
        //查询站内消息表数据列表
        List<UserNotice> userNoticeList = userNoticeService.findUserNoticeList(itemQueryVo);
        //返回对象
        UserDetailResult result = new UserDetailResult();
        //将查询站内消息表数据列表返回对象里面
        result.setUserNoticeList(userNoticeList);

        return  R.ok().data("userNoticeList",JSONObject.toJSONString(result));
    }

}
